package edu.unlv.cs.ladders.entities;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.entity.RooEntity;

import javax.persistence.MappedSuperclass;

import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Column;

@RooJavaBean
@RooToString
@RooEntity
@MappedSuperclass
public abstract class BaseEntity implements Serializable {

	private static final long serialVersionUID = 1L;

	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	private Calendar created;

	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	private Calendar updated;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private Long id;

	@Version
	@Column(name = "version")
	protected Integer version;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Integer getVersion() {
		return version;
	}

	public void setVersion(Integer version) {
		this.version = version;
	}

	@PrePersist
	protected void onCreate() {
		created = Calendar.getInstance();
		updated = Calendar.getInstance();
	}

	@PreUpdate
	protected void onUpdate() {
		updated = Calendar.getInstance();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (obj.getClass() != getClass()) {
			return false;
		}
		BaseEntity rhs = (BaseEntity) obj;
		if (id!=null && id.equals(rhs.id)) {
			return true;
		} else {
			return EqualsBuilder.reflectionEquals(this, rhs);
		}
	}
	@Override
	public int hashCode(){
		int multiplierNonZeroOddNumber = 17;
		int initialNonZeroOddNumber = 29;
		return new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber).append(id).toHashCode();
	}
}
